package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.CountCommunitMapper;
import com.mtnz.njk.Mapper.IntegralManagerMapper;
import com.mtnz.njk.Mapper.IntegralTypeMapper;
import com.mtnz.njk.Mapper.NjkUserMapper;
import com.mtnz.njk.Util.ExcelUtils;
import com.mtnz.njk.entity.CountCommunityEntity;
import com.mtnz.njk.entity.IntegralEntity;
import com.mtnz.njk.entity.NjkUserEntity;
import com.mtnz.njk.model.IntegralOrderModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 积分管理控制层
 * @Author: FBL
 * @CreateDate: 2019\8\23 0023 9:51
 * @Version: 1.0
 */
@Service
public class IntegralManagerService {

    @Autowired
    IntegralManagerMapper integralManagerMapper;

    @Autowired
    IntegralTypeMapper integralTypeMapper;

    @Autowired
    CountCommunitMapper countCommunitMapper;

    @Autowired
    NjkUserMapper userMapper;


    /**
     * 积分订单列表
     *
     * @param key
     * @param beginTime
     * @param endTime
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult integralOrder(String key, String beginTime, String endTime, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询积分订单
        List<CountCommunityEntity> countCommunityEntities = integralManagerMapper.listIntegralOrder(key, beginTime, endTime);
        PageInfo<CountCommunityEntity> countCommunityEntityPageInfo = new PageInfo<>(countCommunityEntities);

        List<CountCommunityEntity> list = countCommunityEntityPageInfo.getList();
        // 置入积分商品信息
        for (CountCommunityEntity countCommunityEntity : list) {
            IntegralEntity integralEntity = integralManagerMapper.selectByPrimaryKey(countCommunityEntity.getCommunityId());
            countCommunityEntity.setIntegralEntity(integralEntity);
        }
        return new ResponseResult(ResponseMessage.OK, countCommunityEntityPageInfo);
    }

    /**
     * 添加物流信息
     *
     * @param expressNum
     * @param expressCompany
     * @return
     * @throws Exception
     */
    public ResponseResult insertExpress(Integer id, String expressNum, String expressCompany) throws Exception {
        String orderNum = expressNum + "," + expressCompany;
        CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
        countCommunityEntity.setId(id);
        countCommunityEntity.setOrderNum(orderNum);
        int i = countCommunitMapper.updateByPrimaryKeySelective(countCommunityEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 积分订单Excel导出
     *
     * @return
     * @throws Exception
     */
    public ResponseResult integralOrderExcel(HttpServletResponse response, String beginTime, String endTime) throws Exception {
        ArrayList<IntegralOrderModel> integralOrderModels = new ArrayList<>();
        // 查询所有积分订单数据
        String key = null;
        List<CountCommunityEntity> countCommunityEntities = integralManagerMapper.listIntegralOrder(key, beginTime, endTime);
        for (CountCommunityEntity countCommunityEntity : countCommunityEntities) {
            boolean sendProduct = false;
            IntegralEntity integralEntity = integralManagerMapper.selectByPrimaryKey(countCommunityEntity.getCommunityId());
            IntegralOrderModel integralOrderModel = new IntegralOrderModel();
            if (integralEntity != null) {
                integralOrderModel.setProductName(integralEntity.getIntegralName());
                if (countCommunityEntity.getNum() != null && !("").equals(countCommunityEntity.getNum()) && countCommunityEntity.getNum().contains(",")) {
                    String num = countCommunityEntity.getNum();
                    String[] split = num.split(",");
                    integralOrderModel.setTradIntegral(Integer.valueOf(split[0]));
                    integralOrderModel.setTradNumber(split[1]);
                }
                integralOrderModel.setTradName(countCommunityEntity.getNickName());
                integralOrderModel.setPhone(countCommunityEntity.getPhone());
                integralOrderModel.setRealityName(countCommunityEntity.getRealityName());
                integralOrderModel.setAddressDetail(countCommunityEntity.getAddressDetail());
                integralOrderModel.setServiceName(countCommunityEntity.getServiceName());
                if (countCommunityEntity.getOrderNum() == null || ("").equals(countCommunityEntity.getOrderNum()) || !countCommunityEntity.getOrderNum().contains(",")) {
                    integralOrderModel.setSendProduct("否");
                } else {
                    sendProduct = true;
                    integralOrderModel.setSendProduct("是");
                }
                if (sendProduct == true) {
                    String orderNum = countCommunityEntity.getOrderNum();
                    String[] orderNums = orderNum.split(",");
                    integralOrderModel.setExpressNumber(orderNums[0]);
                    integralOrderModel.setExpressCompany(orderNums[1]);
                }
                integralOrderModel.setCreateTime(DateUtil.format(countCommunityEntity.getCreateTime(), "yyyy-MM-dd"));
            }
            integralOrderModels.add(integralOrderModel);
        }
        List<String[]> list = new ArrayList<>();
        for (int i = 0; i < integralOrderModels.size(); i++) {
            String[] str = new String[20];
            str[0] = integralOrderModels.get(i).getProductName();
            if (integralOrderModels.get(i).getTradIntegral() != null) {
                str[1] = integralOrderModels.get(i).getTradIntegral().toString();
            } else {
                str[1] = "";
            }
            str[2] = integralOrderModels.get(i).getTradName();
            str[3] = integralOrderModels.get(i).getTradName();
            String NAME = integralOrderModels.get(i).getPhone();
            str[4] = NAME;
            str[5] = integralOrderModels.get(i).getRealityName();
            str[6] = integralOrderModels.get(i).getAddressDetail();
            str[7] = integralOrderModels.get(i).getServiceName();
            str[8] = integralOrderModels.get(i).getSendProduct();
            str[9] = integralOrderModels.get(i).getExpressNumber();
            str[10] = integralOrderModels.get(i).getExpressCompany();
            str[11] = integralOrderModels.get(i).getCreateTime();
            list.add(str);
        }
        String[] heard = {"商品", "兑换积分", "分数", "兑换人昵称", "手机号", "姓名", "地址", "客服", "是否发货", "物流单号", "物流公司", "创建时间"};
        ExcelUtils.createExcelMerge_simple(System.currentTimeMillis() + "_njk.xls", heard, list, response);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 积分变更审核列表
     *
     * @param key
     * @param audit
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult listAuditIntegral(String key, Integer audit, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询积分变更审核列表
        List<CountCommunityEntity> countCommunityEntities = integralManagerMapper.listIntegralUpdate(key, audit);
        PageInfo<CountCommunityEntity> countCommunityEntityPageInfo = new PageInfo<>(countCommunityEntities);
        return new ResponseResult(ResponseMessage.OK, countCommunityEntityPageInfo);
    }

    /**
     * 积分变动审核通过或拒绝
     *
     * @param audit
     * @return
     * @throws Exception
     */
    public ResponseResult auditIntegral(Integer id, Integer audit) throws Exception {
        CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
        countCommunityEntity.setId(id);
        countCommunityEntity.setAudit(audit);
        int i = countCommunitMapper.updateByPrimaryKeySelective(countCommunityEntity);
        if (audit == 1) {
            // 同意审核 修改用户积分
            CountCommunityEntity countCommunity = countCommunitMapper.selectByPrimaryKey(id);
            String userId = countCommunity.getUserId();
            Integer communityType = countCommunity.getCommunityType();
            // 查询用户信息
            NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
            if (communityType == 7) {
                // 增加积分
                userEntity.setIntegral(userEntity.getIntegral() + Integer.valueOf(countCommunity.getNum()));
                // 增加总积分
                userEntity.setTotalIntegral(userEntity.getTotalIntegral() + Integer.valueOf(countCommunity.getNum()));

            }
            if (communityType == 8) {
                // 减少积分
                userEntity.setIntegral(userEntity.getIntegral() - Integer.valueOf(countCommunity.getNum()));
            }
            // 修改用户信息
            userMapper.updateByPrimaryKeySelective(userEntity);
        }

        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL);
    }

}
